package com.md.api.service.impl;

import com.md.api.common.utils.TokenUtil;
import com.md.api.dao.ShoppingCartMapper;
import com.md.api.entity.*;
import com.md.api.entity.dto.ComposeCommitDto;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.util.Page;
import com.md.api.service.CartSevice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * @Author liujie
 * @ClassName ProductServiceImpl
 **/

@Slf4j
@Service
public class CartServiceImpl implements CartSevice {



    @Resource
    TokenUtil tokenUtil;
    @Resource
    ShoppingCartMapper shoppingCartMapper;


    @Override
    public HttpResult addShoppingCart(HttpServletRequest request, ShoppingCart shoppingCart) {
        String userId = tokenUtil.getUserId(request);
        String cartId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        shoppingCart.setCartId(cartId);
//        String userId = request.getHeader("userId");
        shoppingCart.setUserId(userId);
        shoppingCartMapper.insert(shoppingCart);
        return HttpResult.OK;
    }

    @Override
    public HttpResult myCart(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(MyShopCart.class);
        String userId = tokenUtil.getUserId(request);
//        String userId = request.getHeader("userId");
        List<MyShopCart> cartList = shoppingCartMapper.myCart(userId);
        page.setResult(cartList);
        return new HttpResult(page);
    }

    @Override
    public HttpResult removeProduct(HttpServletRequest request, ComposeCommitDto qto) {
        shoppingCartMapper.deleteById(qto.getCartId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult resetProductCount(HttpServletRequest request, ComposeCommitDto qto) {
        shoppingCartMapper.resetProductCount(qto.getCartId(),qto.getCount());
        return HttpResult.OK;
    }
}
